package com.kaishengit.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kaishengit.dao.TaskDao;
import com.kaishengit.dao.UserDao;
import com.kaishengit.pojo.Count;
import com.kaishengit.pojo.Goal;
import com.kaishengit.pojo.Project;
import com.kaishengit.pojo.Task;
import com.kaishengit.pojo.User;
import com.kaishengit.util.DateUtil;

@Service
@Transactional
public class TaskService {
	private TaskDao taskDao;
	private UserDao userDao;
	
	public void save(Task task,String selectname,Goal goal){
		task.setCreatetime(DateUtil.getDate());
		task.setRate(0);
		User user = userDao.findById(Integer.parseInt(selectname));
		task.setUser(user);
		task.setGoal(goal);
		taskDao.save(task);
	}
	
	public void update(Task task,String selectname,Goal goal){
		task.setCreatetime(DateUtil.getDate());
		User user = userDao.findById(Integer.parseInt(selectname));
		task.setUser(user);
		task.setGoal(goal);
		taskDao.update(task);
	}
	
	public void del(int id){
		taskDao.del(id);
	}
	
	public Task findById(int id){
		return taskDao.findById(id);
	}
	
	public List<Task> findAll(){
		return taskDao.findAll();
	}
	
	public List<Task> findById(User user,Project project) {
		return taskDao.findById(user,project);
	}
	
	@Autowired
	public void setTaskDao(TaskDao taskDao) {
		this.taskDao = taskDao;
	}
	@Autowired
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public List<Task> findByGoalId(Goal goal) {
		return taskDao.findByGoalId(goal);
	}

	public Count getCount(List<Task> taskList) {
		Count count = new Count();
		for(Task task : taskList){
			count.setTotalNum(count.getTotalNum()+1);
			count.setTotalrate(count.getTotalrate()+task.getRate());
		}
		if(count.getTotalrate()==0 && count.getTotalNum()== 0){
			count.setTatalave(0);
		}else{
			count.setTatalave(count.getTotalrate()/count.getTotalNum());
		}
		return count;
	}

}
